package com.gxar.quick.ar.server.base.model.protocol.common;

import com.gxar.quick.ar.server.base.model.protocol.ArQuaternion;
import com.gxar.quick.ar.server.base.model.protocol.ArSizeModel;
import com.gxar.quick.ar.server.base.model.protocol.ArVector3;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * AR信息基础模型
 *
 * @author zxh
 * @version 1.0
 * @created 2024/01/02.
 */
@Slf4j
@Data
public abstract class BaseArInfoModel {

    /**
     * 资源地址
     */
    protected String linkUrl;

    /**
     * 世界尺寸
     */
    protected ArSizeModel worldSize;

    /**
     * 原始尺寸
     */
    protected ArSizeModel originSize;

    /**
     * 缩放
     */
    protected ArVector3 scale;

    /**
     * 位移
     */
    protected ArVector3 position;

    /**
     * 旋转
     */
    protected ArVector3 rotation;

    /**
     * 四元数
     */
    protected ArQuaternion quaternion;

    /**
     * 原始四元数
     */
    protected ArQuaternion originQuaternion;


    /**
     * 替换中文、空格等字符，使链接可用
     *
     * @return
     */
    public String getEncodeLinkUrl() {
        if (StringUtils.isEmpty(linkUrl)) {
            log.info("encodeUrl error! input origin url is empty!");
            return "";
        }

        try {
            // 匹配中文和空格的正则表达式
            String zhPattern = "[\u4e00-\u9fa5]+";
            Pattern p = Pattern.compile(zhPattern);
            Matcher m = p.matcher(linkUrl);
            StringBuffer b = new StringBuffer();
            while (m.find()) {
                m.appendReplacement(b, URLEncoder.encode(m.group(0), StandardCharsets.UTF_8.name()));
            }
            m.appendTail(b);
            return b.toString().replaceAll(" ", "%20");
        } catch (UnsupportedEncodingException e) {
            log.error("toEncodeUrl error! origin url:{}", linkUrl);
            return linkUrl;
        }
    }
}
